import { updateProgram } from "@/lib/api/program";
import useFetch from "@/lib/hooks/useFetch";
import useOnUpdated from "@/lib/hooks/useOnUpdated";
import type { IProgram } from "@/lib/types";
import getRequestErrorMessage from "@/lib/utils/getRequestErrorMessage";
import { useMessage } from "@/providers/AntdMessageProvider";
import { tokenAtom } from "@/store/user";
import { Form, InputNumber, Modal } from "antd";
import { useAtomValue } from "jotai";
import { useState } from "react";

type EditProgramCycleModalProps = {
  visible: boolean;
  onClose: () => void;
  program?: IProgram;
  onSuccess: (program: IProgram) => void;
};
export default function EditProgramCycleModal(
  props: EditProgramCycleModalProps,
) {
  const { visible, onClose, program, onSuccess } = props;
  const [loop, setLoop] = useState<number>();
  const token = useAtomValue(tokenAtom);
  const message = useMessage();
  const { isLoading, refetch: handleSave } = useFetch({
    fetchFn: (data: { loop: number; programId: number }) =>
      updateProgram(data, token).then((res) => {
        if (res.code !== 200) {
          throw res;
        }
        return data.loop;
      }),
    onError(error) {
      message.error(getRequestErrorMessage(error));
    },
    onSuccess(loop) {
      message.success("操作成功");
      onSuccess({ ...program!, loop });
    },
  });

  function handleSubmit() {
    if (typeof loop === "undefined") {
      message.info("请输入循环数！");
      return;
    }
    handleSave({ programId: program!.programId, loop });
    onClose();
  }

  useOnUpdated(() => {
    if (visible && program) {
      setLoop(program.loop);
    }
  }, [visible, program]);

  return (
    <Modal
      title="循环"
      open={visible}
      onClose={onClose}
      onCancel={onClose}
      onOk={handleSubmit}
      confirmLoading={isLoading}
      afterClose={() => setLoop(undefined)}
      destroyOnClose
    >
      <Form>
        <Form.Item label={`${program?.programName} [循环数]`}>
          <InputNumber
            className="w-full"
            value={loop}
            onChange={(value) => setLoop(value || undefined)}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
}
